package com.cari.oa.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.cari.oa.domain.SysActionEntity;
import com.cari.oa.domain.SysModuleEntity;
import com.cari.oa.domain.SysRoleEntity;
import com.cari.oa.service.SysActionService;
import com.cari.oa.service.SysModuleService;
import com.cari.oa.service.SysRoleService;
import com.cari.oa.util.Contants;
import com.cari.oa.util.RoleActionTreeNode;
import com.cari.oa.util.Utils;

/**
 * 系统用户controller
 * User: yexuhui
 * Date: 2012-12-26
 * Time: 下午2:59:41
 */
@Controller
@SessionAttributes("username")
public class SysRoleController {

	@Resource
	private SysRoleService sysRoleService;
	@Resource
	private SysModuleService sysModuleService;
	@Resource
	private SysActionService sysActionService;
	
	public static final String MODULE_NAME = "SYS_ROLE_MANAGE";
	
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
    
    @RequestMapping("/system/role/list.do")
    public String list(String enname, String alias, Integer curPage, ModelMap modelMap) {
        if(curPage == null) curPage = 1;
        long totalRecords = sysRoleService.getCount(enname, alias);
        long totalPage = totalRecords / Contants.PAGE_SIZE + (totalRecords % Contants.PAGE_SIZE != 0 ? 1 : 0);
        
        List<SysRoleEntity> roleList = sysRoleService.getPage(enname, alias, curPage, Contants.PAGE_SIZE);

        modelMap.addAttribute("roleList", roleList);
        modelMap.addAttribute("curPage", curPage);
        modelMap.addAttribute("totalPage", totalPage);
        modelMap.addAttribute("totalRecords", totalRecords);

        modelMap.addAttribute("enname", enname);
        modelMap.addAttribute("alias", alias);

        return "system/role/list";
    }   
    
    @RequestMapping(value = "/system/role/view.do", method = RequestMethod.GET)
    public String enterView(String id, ModelMap modelMap) {
    	SysRoleEntity role = sysRoleService.getById(id);
        modelMap.addAttribute("role", role);
        return "system/role/view";
    }    
    
    @RequestMapping(value = "/system/role/insert.do", method = RequestMethod.GET)
    public String enterInsert(String qs, ModelMap modelMap) {
        modelMap.addAttribute("qs", qs);
        return "system/role/insert";
    }
    
    @RequestMapping(value = "/system/role/edit.do", method = RequestMethod.GET)
    public String enterEdit(String id, String qs, ModelMap modelMap) {
    	SysRoleEntity role = sysRoleService.getById(id);
        modelMap.addAttribute("role", role);
    	modelMap.addAttribute("qs", qs);
        return "system/role/edit";
    } 
    
    @RequestMapping(value = "/system/role/action.do", method = RequestMethod.GET)
    public String enterAction(String enname, String qs, ModelMap modelMap) {
    	List<RoleActionTreeNode> nodes = new ArrayList<RoleActionTreeNode>();
    	
    	List<SysModuleEntity> allTopModules = sysModuleService.getAllTopModules();
    	for (SysModuleEntity m : allTopModules) {
    		RoleActionTreeNode node = new RoleActionTreeNode(m.getId(), m.getParentId(), m.getEnname(), m.getAlias(), 
    				true, true, false);
    		nodes.add(node);
		}
    	
    	Map<String, String> mNameIdMap = new HashMap<String, String>();
    	List<SysModuleEntity> allSubModules = sysModuleService.getAllSubModules();
    	for (SysModuleEntity m : allSubModules) {
    		RoleActionTreeNode node = new RoleActionTreeNode(m.getId(), m.getParentId(), m.getEnname(), m.getAlias(), 
    				false, true, false);
    		nodes.add(node);
    		mNameIdMap.put(m.getEnname(), m.getId());
		}
    	
    	List<SysActionEntity> allActions = sysActionService.getAll();
    	List<SysActionEntity> roleActions = sysActionService.getActionsByRole(enname);
    	for (SysActionEntity allActionEntity : allActions) {
			boolean isFind = false;
			for (SysActionEntity roleActionEntity : roleActions) {
				if(allActionEntity.getId().equals(roleActionEntity.getId())) {
					isFind = true;
					break;
				}
			}
			
    		RoleActionTreeNode node = new RoleActionTreeNode(allActionEntity.getId(), 
    				mNameIdMap.get(allActionEntity.getModuleName()), allActionEntity.getEnname(), 
    				allActionEntity.getAlias(), false, false, isFind);
    		nodes.add(node);			
		}
    	
        modelMap.addAttribute("nodes", nodes);
        modelMap.addAttribute("enname", enname);
    	modelMap.addAttribute("qs", qs);
        return "system/role/action";
    }      
    
    @RequestMapping(value = "/system/role/insert.do", method = RequestMethod.POST)
    @ResponseBody
    public String postInsert(@ModelAttribute("username") String username, 
    		@Valid SysRoleEntity sysRoleEntity, BindingResult result) {
        if(result.hasFieldErrors())
            return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());

        if (sysRoleService.existByEnname(sysRoleEntity.getEnname()))
            return Utils.errorJsonResp("系统角色英文名已存在");

        sysRoleService.insert(sysRoleEntity);
        
        SysOperLogController.addOperLog(username, MODULE_NAME, "新增角色" + sysRoleEntity.getEnname());
        return Utils.normalJsonResp();
    } 
    
    @RequestMapping(value = "/system/role/edit.do", method = RequestMethod.POST)
    @ResponseBody
    public String postEdit(@ModelAttribute("username") String username, 
    		@Valid SysRoleEntity sysRoleEntity, BindingResult result) {
    	if(result.hasFieldErrors())
            return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());
        
    	sysRoleService.update(sysRoleEntity);
    	
    	SysOperLogController.addOperLog(username, MODULE_NAME, "修改角色" + sysRoleEntity.getEnname());
        return Utils.normalJsonResp();
    }   
    
    @RequestMapping(value = "/system/role/delete.do")
    @ResponseBody
    public String delete(@ModelAttribute("username") String username, String id) {
    	SysRoleEntity sysRoleEntity = sysRoleService.getById(id);
        if(sysRoleEntity == null) return Utils.errorJsonResp("该角色已不存在，请刷新页面");

        if(sysRoleService.isRoleUsedByUser(sysRoleEntity.getEnname()))
            return Utils.errorJsonResp("还有用户关联该角色，请先解除关联，才能删除");

        sysRoleService.delete(sysRoleEntity);
        
        SysOperLogController.addOperLog(username, MODULE_NAME, "删除角色" + sysRoleEntity.getEnname());
        return Utils.normalJsonResp();
    }    
    
    @RequestMapping(value = "/system/role/action.do", method = RequestMethod.POST)
    @ResponseBody
    public String postAction(@ModelAttribute("username") String username, 
    		String enname, String actions, ModelMap modelMap) {
    	String[] actionArr = actions.split(";");
    	if(actionArr.length > 0)
    		sysActionService.resetRoleActionRel(enname, Arrays.asList(actionArr));
    	
    	SysOperLogController.addOperLog(username, MODULE_NAME, "配置角色" + enname + "的action");
    	return Utils.normalJsonResp();
    }
}
